<template>
  <div class="login_bg">
    <a-card class="login_card">
      <div class="login_box_title">
        <div class="text">账号登录</div>
        <div class="english">User account login</div>
      </div>
      <a-form :model="loginForm" ref="formRef" :rules="rulesForm">
        <a-form-item name="account">
          <a-input v-model:value="loginForm.account" prefix-icon="el-icon-user" :placeholder="$t('账号')"/>
        </a-form-item>
        <a-form-item name="password">
          <a-input-password show-password v-model:value="loginForm.password" prefix-icon="el-icon-lock"
                            :placeholder="$t('密码')"/>
        </a-form-item>
        <a-form-item name="validateCode">
          <div style="display: flex;height: 32px">
            <a-input v-model:value="loginForm.validateCode" style="width: 70%" :placeholder="$t('验证码')"/>
            <img @click="fetchCode" :src="codeUrl" style="width: 30%;height: 100%;cursor: pointer"/>
          </div>
        </a-form-item>
        <a-form-item>
          <a-button :loading="loginLoading" style="width: 100%" @click="submitLoginForm()" type="primary">
            {{ $t('登录') }}
          </a-button>
        </a-form-item>
      </a-form>

      <a-modal v-model:visible="firstLoginVisible" :title="$t('修改密码')"
               :confirmLoading="firstLoginLoading"
               @ok="firstStepConfirm"
               width="50%"
               :mask-closable="false"
               :okText="firstLoginStepCurrent === 0 ? $t('下一步') : $t('确认')"
               :after-close="updateClearForm">
        <a-steps :current="firstLoginStepCurrent" size="small">
          <a-step :title="$t('修改密码')"></a-step>
          <a-step :title="$t('绑定谷歌验证器')"></a-step>

        </a-steps>
        <div style="margin-top:15px">
          <!--           修改密码-->
          <a-form
              v-if="firstLoginStepCurrent === 0"
              :model="updatePasswordForm"
              ref="passwordRef"
              :rules="updatePasswordRulesForm"
              :labelCol="{span:5}"
          >
            <a-form-item :label="$t('原密码')" name="password">
              <a-input-password v-model:value="updatePasswordForm.password"/>
            </a-form-item>
            <a-form-item :label="$t('新密码')" name="newPassword">
              <a-input-password v-model:value="updatePasswordForm.newPassword"/>
            </a-form-item>
            <a-form-item :label="$t('确认密码')" name="confirmPassword">
              <a-input-password v-model:value="updatePasswordForm.confirmPassword"/>
            </a-form-item>
          </a-form>
          <!--          绑定谷歌验证器-->
          <div v-else>
            <div style="text-align: center;margin: 15px 0">
              <img style="height: 120px;width:120px" :src="ggBind.qrCodeUrl"/>
              <div style="font-size: 10px;margin-top: 10px;color: #7b7b7b">{{ $t('请用谷歌验证器扫一扫') }}</div>
              <div style="font-size: 10px;margin-top: 5px;color: red">
                <span>{{ $t('提示') }} :</span>
                <span >{{ $t('为确保账户安全，请勿向他人泄露该二维码和秘钥') }}</span>
              </div>
            </div>
            <div style="display: flex;justify-content:center">
              <a-form style="width:500px;" :labelCol="{span:5}">
                <a-form-item :label="$t('秘钥')">
                  <a-textarea :rows="5" v-model:value="ggBind.key"/>
                </a-form-item>
                <a-form-item :label="$t('谷歌验证码')">
                  <a-input v-model:value="ggBind.code"/>
                </a-form-item>
              </a-form>
            </div>
          </div>
        </div>
      </a-modal>
    </a-card>

  </div>
</template>

<script>
import {ref, reactive, onMounted, toRefs, h} from 'vue'
import {Input, message, Modal, InputPassword} from "ant-design-vue";
import {useI18n} from 'vue-i18n'
import router from '../../router/index'
import {
  getLoginCode,
  onLogin,
  updatePassword,
  fetchGoogleSecretKey,
  fetchGoogleSecretQrCode,
  bindGoogleSecret,
  secondaryLogin
} from "../../api";
import i18n from "../../locale";

const $t = i18n.global.t
export default {
  name: "Login",
  setup() {
    const codeUrl = ref('')
    const passwordRef = ref(null)
    const {t} = useI18n()
    const loginForm = reactive({
      key: '',
      account: '',
      password: '',
      validateCode: ''
    })
    const updatePasswordForm = reactive({
      password: '',
      newPassword: '',
      confirmPassword: ''
    })
    const firstLogin = reactive({
      firstLoginVisible: false,
      firstLoginStepCurrent: 0,
      firstLoginLoading: false
    })
    const ggBind = reactive({
      key: '',
      qrCodeUrl: '',
      code: '',
      secondaryCode: ''
    })
    const loginLoading = ref(false)
    const formRef = ref(null)
    const rulesForm = reactive({
      account: {required: true, message: t('请输入账号'), trigger: 'blur'},
      password: {required: true, message: t('请输入密码'), trigger: 'blur'},
      validateCode: {required: true, message: t('请输入验证码'), trigger: 'blur'},
    })
    const updatePasswordRulesForm = reactive({
      password: [
        {required: true, message: '请输入原密码', trigger: 'blur'},
      ],
      newPassword: [
        {required: true, message: '请输入新密码', trigger: 'blur'},
        {min: 6, max: 15, message: '密码长度为6-15位', trigger: 'blur'},
      ],
      confirmPassword: [
        {required: true, message: '请输入新密码', trigger: 'blur'},
        {min: 6, max: 15, message: '密码长度为6-15位', trigger: 'blur'},
      ]
    })
    const fetchCode = async () => {
      loginForm.key = new Date().getTime().toString() + GetRandomNum(0, 9999)
      const res = await getLoginCode({key: loginForm.key})
      if (res) {
        codeUrl.value = 'data:image/png;base64,' + btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''))
      }
    }
    const GetRandomNum = (Min, Max) => {
      let Range = Max - Min;
      let Rand = Math.random();
      return (Min + Math.round(Rand * Range)).toString();
    }
    const submitLoginForm = async () => {
      formRef.value.validate().then(async () => {
        loginLoading.value = true
        const res = await onLogin(loginForm)
        if (res.code === 200) {
          // isUpdatePassword 0 首次登录 1 非首次登录
          const {systemUser, token, permission, second_login_token} = res.data
          // 未开启二次登录
          if (!second_login_token) {
            sessionStorage.setItem('userInfo', JSON.stringify(systemUser))
            sessionStorage.setItem('token', token)
            sessionStorage.setItem('menuList', JSON.stringify(permission))
            loginLoading.value = false
            if (systemUser.isUpdatePassword === 0) {
              firstLogin.firstLoginVisible = true
            } else if (systemUser.isUpdatePassword === 1) {
              message.success($t('登录成功'))
              router.push('/index')
            }
          } else {
            Modal.confirm({
              title: h('div', {
                style: {
                  fontSize: '14px'
                }
              }, $t('为确保账号安全，系统需要进行二次校验')),
              content: h(Input, {
                placeholder: $t('验证码'),
                onInput: (value) => {
                  const val = value.target.value
                  if (!(/[^\d]/g).test(val)) {
                    ggBind.secondaryCode = val
                  } else {
                    ggBind.secondaryCode = ''
                  }
                },
              }),
              async onOk() {
                if (!ggBind.secondaryCode) return message.error($t('请填写验证码'))
                const res = await secondaryLogin({
                  second_login_token: second_login_token,
                  code: ggBind.secondaryCode
                })
                if (res.code === 200) {
                  const {systemUser, token, permission} = res.data
                  message.success($t('登录成功'))
                  ggBind.secondaryCode = ''
                  sessionStorage.setItem('userInfo', JSON.stringify(systemUser))
                  sessionStorage.setItem('token', token)
                  sessionStorage.setItem('menuList', JSON.stringify(permission))
                  router.push('/index')
                }
                fetchCode()
              }
            })
          }
          loginLoading.value = false
        } else {
          loginLoading.value = false
          fetchCode()
        }
      })
    }
    // 步骤条提交
    const firstStepConfirm = () => {
      if (firstLogin.firstLoginStepCurrent === 0) {
        updatePasswordConfirm()
      } else {
        bindGGConfirm()
      }
    }

    // 修改密码提交
    const updatePasswordConfirm = () => {
      passwordRef.value.validate().then(async () => {
        firstLogin.firstLoginLoading = true
        const res = await updatePassword(updatePasswordForm)
        if (res.code === 200) {
          message.success($t('重置密码成功'))
          fetchGGInfo()
        }
        firstLogin.firstLoginLoading = false
      })
    }
    // 获取谷歌验证二维码与密钥
    const fetchGGInfo = async () => {
      const keyRes = await fetchGoogleSecretKey()
      const {secretKey, secretQrCodeStr} = keyRes.data
      const qrCodeRes = await fetchGoogleSecretQrCode({secretQrCode: secretQrCodeStr})
      ggBind.qrCodeUrl = 'data:image/png;base64,' + btoa(new Uint8Array(qrCodeRes).reduce((data, byte) => data + String.fromCharCode(byte), ''))
      ggBind.key = secretKey
      firstLogin.firstLoginStepCurrent = 1
    }
    const bindGGConfirm = async () => {
      const res = await bindGoogleSecret({
        secretKey: ggBind.key,
        code: ggBind.code
      })
      if (res.code === 200) {
        message.success($t('绑定谷歌验证器成功,请重新登录'))
        fetchCode()
        firstLogin.firstLoginVisible = false
      }
    }
    const updateClearForm = () => {
      if (passwordRef.value) {
        passwordRef.value.resetFields()
      }
      firstLogin.firstLoginStepCurrent = 0
      ggBind.qrCodeUrl = ''
      ggBind.key = ''
      ggBind.code = ''
    }
    onMounted(() => {
      fetchCode()
      document.onkeydown = (ev) => {
        if (ev.key === 'Enter') {
          submitLoginForm()
        }
      }
    })
    return {
      ...toRefs(firstLogin),
      ggBind,
      passwordRef,
      updatePasswordForm,
      updatePasswordRulesForm,
      firstStepConfirm,
      updateClearForm,
      loginForm,
      codeUrl,
      submitLoginForm,
      rulesForm,
      fetchCode,
      loginLoading,
      formRef
    }
  }
}
</script>

<style scoped lang="less">
@media screen and (max-width: 1024px ) {
  .login_bg {
    min-height: 100vh;
  }

  .login_card {
    left: 50% !important;
    width: 320px !important;
    transform: translate(-50%, -50%) !important;
  }
}

.login_bg {
  min-height: 100vh;
  min-width: 100%;
  background-image: url("../../assets/login_bg.png");
  background-size: 100% 100%;
  background-color: #f0f2f5;

  .login_card {
    position: absolute;
    right: 10%;
    top: 50%;
    transform: translateY(-50%);
    width: 350px;

    .login_box_title {
      text-align: center;
      margin-bottom: 20px;

      .text {
        font-size: 24px;
        letter-spacing: 1px;
        color: #66bfff;
      }

      .english {
        color: #66bfff;
        margin-top: 5px;
        font-size: 10px;
      }
    }

    .login_box_title::before {
      content: '';
      width: 50px;
      height: 1px;
      border-bottom: 1px solid;
      display: block;
      position: absolute;
      left: 35px;
      top: 45px;
      color: #66bfff;
    }

    .login_box_title::after {
      content: '';
      width: 50px;
      height: 1px;
      border-bottom: 1px solid;
      display: block;
      position: absolute;
      right: 35px;
      top: 45px;
      color: #66bfff;
    }

  }
}
</style>
